<template>
  <div class="platform-attribute">
    <div class="side">
      <div class="radio-goup">
        <div
          @click="changeAttributeType('unmodifyStastsProductList')"
          :class="{ 'radio-active': attributeType == 'unmodifyStastsProductList' }"
        >
          未修改({{ platformAttributeData.unmodifyStastsProductNum }})
        </div>
        <div
          @click="changeAttributeType('modifyStastsProductList')"
          :class="{ 'radio-active': attributeType == 'modifyStastsProductList' }"
        >
          已修改({{ platformAttributeData.modifyStastsProductNum }})
        </div>
        <div
          @click="changeAttributeType('noFillOutStastsProductList')"
          :class="{ 'radio-active': attributeType == 'noFillOutStastsProductList' }"
        >
          未填写({{ platformAttributeData.noFillOutStastsProductNum }})
        </div>
      </div>
      <el-scrollbar height="calc(100vh - 130px)">
        <div
          :class="{
            'attribute-item': true,
            'attribute-item-active':
              attributeType !== 'noFillOutStastsProductList'
                ? item.childStastsId == checkedAttr.childStastsId
                : item.stastsId == checkedAttr.stastsId
          }"
          v-for="(item, index) in platformAttributeList"
          :key="index"
          @click="changeAttribute(item)"
        >
          {{ getPlatformAttributeName(item) }}
        </div>
        <el-empty v-if="!platformAttributeList.length" />
      </el-scrollbar>
    </div>
    <div class="container">
      <div class="filter">
        <div class="checked">已勾选：{{ checkedList.length }}</div>
        <el-button plain type="primary" @click="openBacthEdit"> 批量修改平台属性 </el-button>
        <el-form-item label="在售价" style="min-width: 300px">
          <el-space>
            <el-input placeholder="请输入" v-model="filterParmas.minSalePrice" @blur="getPlatformAttribute" />
            ——
            <el-input placeholder="请输入" v-model="filterParmas.maxSalePrice" @blur="getPlatformAttribute" />
          </el-space>
        </el-form-item>
        <el-input placeholder="商品名称/工厂名称/商品id/品牌/分类" v-model="filterParmas.searchKey" @blur="getPlatformAttribute">
        </el-input>
        <el-button link type="primary" @click="openFilter"
          >更多筛选 <el-icon> <ArrowRight /> </el-icon
        ></el-button>
      </div>
      <el-row class="table-head">
        <el-col :span="8">
          <div class="all">
            <el-checkbox @change="setCheckAll" v-model="checkAll" :indeterminate="isIndeterminate"></el-checkbox>
          </div>
          <span class="image-title">商品图</span>
          <span>商品信息</span>
        </el-col>
        <el-col :span="4"> 价格 </el-col>
        <el-col :span="3"> 品牌 </el-col>
        <el-col :span="6"> 商品属性 </el-col>
        <el-col :span="3"> 操作 </el-col>
      </el-row>
      <el-scrollbar class="table-list">
        <el-empty description="空" v-if="!goodsList.length" />
        <el-checkbox-group v-model="checkedList">
          <div class="goods" v-for="goods in goodsList" :key="goods">
            <div class="business-name">
              <div class="name">
                <div class="all"><el-checkbox @change="checked" :value="goods.productId" /></div>
                {{ goods.productName }}
              </div>
            </div>
            <el-row>
              <el-col :span="8">
                <img class="image" :src="goods.mainPicUrl || defaultImage" alt="" />
                <div class="info" style="white-space: break-spaces; word-break: break-all">
                  <div>型号：{{ goods.modeCode }}</div>
                  <div v-for="(item, index) in goods.specifications" :key="index">
                    {{ item.specificationName }}：{{ item.specificationVal }}
                  </div>
                </div>
              </el-col>
              <el-col :span="4">
                {{ goods.businessLowestPrice }}
              </el-col>
              <el-col :span="3" style="white-space: break-spaces; word-break: break-all">
                {{ goods.brandName }}
              </el-col>
              <el-col :span="6">
                <p class="text-break pl10 pr10">{{ goods.stastsVals }}</p>
              </el-col>
              <el-col :span="3">
                <el-button type="primary" link size="small" @click="openEditAtrr(goods)">编辑</el-button>
              </el-col>
            </el-row>
          </div>
        </el-checkbox-group>
        <div class="pagination">
          <el-pagination
            v-model:current-page="filterParmas.page"
            v-model:page-size="filterParmas.size"
            :page-sizes="[10, 20, 100, 200]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @change="getGoodsList"
          />
        </div>
      </el-scrollbar>
    </div>

    <!-- 单个 -->
    <el-drawer v-model="editAtrrVisible" :size="500" class="platformAttribute-drawer" :before-close="cancelClick">
      <template #header>
        <TitleView title="平台属性" />
      </template>
      <template #default>
        <div class="gray-bg mb20">
          <GoodsDetail :goods="currentGoods" />
        </div>
        <!-- <AtrrListCopy :data="atrrData" v-model:form="editAtrrForm" :categoryList="categoryList" /> -->
        <AtrrList ref="editAttrOneRef" :filterData="atrrData" :goods="currentGoods" />
      </template>
      <template #footer>
        <el-button @click="cancelClick">取消</el-button>
        <el-button type="primary" @click="editComfirm">确认修改</el-button>
      </template>
    </el-drawer>

    <!-- 批量 -->
    <el-drawer v-model="bacthEditAtrrVisible" :size="900" class="batch-edit" :before-close="cancelClick2">
      <template #header>
        <TitleView title="批量修改" />
      </template>
      <div class="tip">
        <el-icon> <WarningFilled /> </el-icon>选择对应平台属性标签后，将替换到所选商品中，点击保存正式修改，请根据需要调整！
      </div>
      <div class="batch-edit_content">
        <el-scrollbar class="atrr">
          <AtrrList ref="editAttrAnyRef" :filterData="atrrData" />
        </el-scrollbar>
        <el-scrollbar class="goods-list">
          <div class="goods-list_item" v-for="(goods, index) in bacthGoodsList" :key="index">
            <GoodsDetail :goods="goods">
              <template #default>
                <div class="atrr-str">
                  {{ goods.stastsVals }}
                  <img @click="delBacth(goods.productId)" src="../../../../assets/images/mall/del.png" alt="" />
                </div>
              </template>
            </GoodsDetail>
          </div>
        </el-scrollbar>
      </div>
      <template #footer>
        <el-button @click="cancelClick2">取消</el-button>
        <el-button type="primary" @click="batchEditAtrr">确认修改</el-button>
      </template>
    </el-drawer>
    <!-- 属性筛选 -->
    <attrFilter ref="attrFilterRef" v-model:isOpen="isOpenAttrFilter" :filterData="filterData" @changeAttr="changeAttr">
      <template #classify>
        <div class="pl20 pr20">
          <p style="color: #86909c; font-size: 16px">分类</p>
          <el-cascader
            v-model="category"
            style="width: 100%"
            :options="categoryList"
            clearable
            :props="{ label: 'name', value: 'categoryId' }"
            @change="
              () => {
                getFilterData(category);
              }
            "
          />
        </div>
      </template>
    </attrFilter>
    <!-- <el-drawer v-model="moreFilterVisible" :size="500" class="platformAttribute-drawer">
      <template #header>
        <TitleView title="筛选更多" />
      </template>
      <MoreFilter
        v-model:form="filterIds"
        v-model:categoryId="categoryId"
        :data="filterData"
        :categoryList="categoryList"
        :isEdit="!checkedAttr.categoryId"
        @queryFilterList="getFilterData"
      />
      <template #footer>
        <el-button @click="closeFilter">取消</el-button>
        <el-button type="primary" @click="getGoodsList">确定</el-button>
      </template>
    </el-drawer> -->
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import TitleView from "@/components/TitleView/index.vue";
import GoodsDetail from "./GoodsDetail.vue";
import {
  getPlatformAttributeList,
  getCategoryTreeList,
  getPlatformProductList,
  saveEditPlatformAtrr
} from "@/api/products/manage";
import MoreFilter from "./MoreFilter.vue";
import { queryStastsList } from "@/api/products/selection";
import { getStastsListAll } from "@/api/products/specifications";
import AtrrList from "./AtrrList.vue";
import AtrrListCopy from "./AtrrListCopy.vue";
import { ElMessage } from "element-plus";
import attrFilter from "@/views/products/selection/components/attrFilter.vue";

const editAttrOneRef = ref();
const editAttrAnyRef = ref();
const goodsList = ref([{}]);
const checkedList = ref([]);
const props = defineProps(["defaultImage"]);
const editAtrrVisible = ref(false);
const moreFilterVisible = ref(false);
const platformAttributeData = ref({});
const attributeType = ref("unmodifyStastsProductList");
const platformAttributeList = computed(() => platformAttributeData.value[attributeType.value] || []);
const checkedAttr = ref({}); // 当前选中的属性
const filterParmas = ref({
  page: 1,
  size: 10
}); // 表格头的筛选参数
const categoryList = ref([]); // 分类列表
const currentGoods = ref({}); // 当前商品
const bacthEditAtrrVisible = ref(false);
const editAtrrForm = ref([]);
const total = ref(0);
const bacthEditAtrrForm = ref([]);
const categoryId = ref([]);

const atrrData = ref([]);
const filterIds = ref({});
const isIndeterminate = ref(false);
const checkAll = ref(false);
const isOpenAttrFilter = ref(false); //是否打开更多筛选抽屉
const attrFilterRef = ref();
const attrList = ref([]); //筛选属性列表
const _filterVal = ref([]); //用户选中的筛选属性值
const _filterVal3 = ref([]); //用户选中的3级筛选属性值
const _brandIds = ref([]);
const category = ref([]);

/**重置“更多筛选”属性、品牌相关数据 */
const resetFilterAttr = () => {
  _filterVal.value = [];
  _filterVal3.value = [];
  _brandIds.value = [];
  attrFilterRef.value.reset();
};

//属性筛选id改变时的回调
const changeAttr = ({ filterVal, filterVal3, brandIds }) => {
  console.log("子组件返回的数据===", filterVal, filterVal3);
  _filterVal.value = filterVal;
  _filterVal3.value = filterVal3;
  _brandIds.value = brandIds;

  filterDataSubmit(); //属性筛选接口请求
};

/**
 *用户进行属性值勾选，筛选数据
 * @param init 为false时，不重置当前分页； 为true时，重置当前分页为1
 */
const filterDataSubmit = (init = true) => {
  // 属性值筛选数据
  // console.log("属性值筛选数据", _filterVal.value, _filterVal3.value);
  const attrIds2 = _filterVal.value.flat(); //选中的二级属性ids
  for (let ids2 of attrIds2) {
    const str = _filterVal3.value.find(item => typeof item === "string" && item.includes(ids2));
    !str && _filterVal3.value.push(ids2);
  }
  if (init) filterParmas.value.page = 1;

  getGoodsList();
};

const changeAttribute = item => {
  // console.log("点击了分类属性===", item);
  goodsList.value = [];
  checkedAttr.value = item;
  resetFilterAttr();
  getGoodsList();
  filterIds.value = {};
  checkedList.value = [];
  checkAll.value = false;
  isIndeterminate.value = false;
};
/**
 * 获取平台属性
 */
const getPlatformAttribute = async () => {
  try {
    const res = await getPlatformAttributeList();
    platformAttributeData.value = res.data || {};
    if (platformAttributeList.value.length) changeAttribute(platformAttributeList.value[0]);
  } catch (error) {
    console.log(error);
  }
};
/**
 * 获取拼接的属性名称
 */
const getPlatformAttributeName = item => {
  return (
    (item.type == 1 ? "通用属性" : item.categoryName) +
    "-" +
    (item.childStastsName ? item.stastsName + "-" + item.childStastsName : item.stastsName) +
    "(" +
    (attributeType.value == "unmodifyStastsProductList"
      ? item.unmodifyProductNum
      : attributeType.value == "modifyStastsProductList"
        ? item.modifyProductNum
        : item.fillOutProductNum) +
    ")"
  );
};
/**
 * 选中
 */
const checked = () => {
  checkAll.value = checkedList.value.length == goodsList.value.length;
  isIndeterminate.value = checkedList.value.length != goodsList.value.length && checkedList.value.length != 0;
};
/**
 * 设置全选
 */
const setCheckAll = () => {
  checkedList.value = checkAll.value ? goodsList.value.map(item => item.productId) : [];
  isIndeterminate.value = false;
};
const bacthGoodsList = computed(() => {
  return goodsList.value.filter(item => checkedList.value.includes(item.productId));
});
/**
 * 打开修改属性弹窗
 */
const openEditAtrr = item => {
  currentGoods.value = { ...item };
  editAtrrForm.value = [];
  getPlatformAttributeListDatail();
  editAtrrVisible.value = true;
};
const statsList = computed(() => {
  return editAtrrForm.value.map(v => ({
    ...v,
    stastsVal: v.stastsVal.join(","),
    stastsValId: v.stastsValId.join(",")
  }));
});
const delBacth = productId => {
  checkedList.value = checkedList.value.filter(v => v !== productId);
  if (!checkedList.value.length) {
    checkAll.value = false;
    isIndeterminate.value = false;
    bacthEditAtrrVisible.value = false;
  }
};
/**
 * 修改属性
 */
const editComfirm = async () => {
  try {
    const list = editAttrOneRef.value.getAttrL2();
    const params = {
      productIds: [currentGoods.value.productId],
      statsList: list
    };
    // console.log("确认修改参数===", params);
    // return;
    await saveEditPlatformAtrr(params);
    getPlatformAttribute();
    getGoodsList();
    ElMessage.success("操作成功");
    editAtrrVisible.value = false;
    editAttrOneRef.value.reset();
  } catch (error) {}
};
const cancelClick = () => {
  editAtrrVisible.value = false;
  editAttrOneRef.value.reset();
};
const cancelClick2 = () => {
  bacthEditAtrrVisible.value = false;
  editAttrAnyRef.value.reset();
};

/**
 * 批量修改属性
 */
const batchEditAtrr = async () => {
  try {
    const list = editAttrAnyRef.value.getAttrL2();
    const params = {
      productIds: checkedList.value,
      statsList: list
    };
    await saveEditPlatformAtrr(params);
    getPlatformAttribute();
    ElMessage.success("操作成功");
    bacthEditAtrrVisible.value = false;
    editAttrAnyRef.value.reset();
  } catch (error) {}
};

/**
 * 改变属性修改类型
 */
const changeAttributeType = type => {
  filterIds.value = {};
  goodsList.value = [];
  total.value = 0;

  attributeType.value = type;
  checkedAttr.value = platformAttributeList.value[0];
  resetFilterAttr();
  getGoodsList();
};
/**
 * 筛选更多列表数据
 */
const filterData = ref([]);
/**
 * 获取筛选更多列表
 */
const getFilterData = async id => {
  try {
    const params = {};
    if (checkedAttr.value.categoryId) params.categoryId = checkedAttr.value.categoryId;
    else if (categoryId.value?.length) params.categoryId = categoryId.value[categoryId.value.length - 1];
    else params.categoryId = undefined;
    const res = await queryStastsList(id ? { categoryId: id[id.length - 1] } : params);
    filterData.value = res.data;
  } catch (error) {
    console.log(error);
  }
};
/**
 * 打开更多筛选
 */
const openFilter = async () => {
  getFilterData();
  isOpenAttrFilter.value = true;
};
/**
 * 打开批量修改弹窗
 */
const openBacthEdit = () => {
  getPlatformAttributeListDatail();
  editAtrrForm.value = [];
  bacthEditAtrrVisible.value = true;
};
/**
 * 获取分类树
 */
const getCategoryTreeData = async () => {
  const res = await getCategoryTreeList("");
  categoryList.value = res.data;
};
/**
 * 格式化参数
 */
const formatParams = params => {
  const result = [checkedAttr.value.stastsValId];
  for (let key in params) {
    if (Array.isArray(params[key])) {
      result.push(...params[key]);
    } else if (typeof params[key] === "object") {
      for (let childkey in params[key]) {
        result.push([childkey, params[key][childkey]].join("-"));
      }
    } else if (params[key]) {
      result.push(params[key]);
    }
  }
  return result;
};
const closeFilter = () => {
  filterIds.value = {};
  moreFilterVisible.value = false;
};
/**
 * 获取可设置的平台属性
 */
const getPlatformAttributeListDatail = async () => {
  const res = await getStastsListAll({ isPlatform: 1, categoryId: checkedAttr.value?.categoryId });
  atrrData.value = res.data;
  // console.log("atrrData======", atrrData.value);
  echo();
};
/**
 * 获取商品列表
 */
const getGoodsList = async () => {
  moreFilterVisible.value = false;
  if (!checkedAttr.value) return;
  if (filterParmas.value.minSalePrice > filterParmas.value.maxSalePrice) return ElMessage.error("最小值不能大于最大值！");
  const stastsIdsStr = formatParams(filterIds.value);
  const isModify = ["unmodifyStastsProductList", "modifyStastsProductList", "noFillOutStastsProductList"].indexOf(
    attributeType.value
  );
  try {
    checkedAttr.value;
    const arr = checkedAttr.value?.stastsValId ? [checkedAttr.value?.stastsValId] : [];
    const res = await getPlatformProductList({
      ...filterParmas.value,
      // stastsIdsStr,
      isModify,
      categoryId: checkedAttr.value.categoryId,
      stastsIdsStr: [...new Set([..._filterVal3.value, ...arr])], //属性筛选ids
      brandIds: _brandIds.value, //品牌id
      firstStastsId: attributeType.value === "noFillOutStastsProductList" ? checkedAttr.value?.stastsId : "" //如果是“未填写”，则传一级属性id
    });
    goodsList.value = res.data.records;
    total.value = res.data.total;
  } catch (error) {}
};
/**
 * 回显
 */
const echo = () => {
  if (!currentGoods.value.stastsPlatformValIds) return;
  const idsArr = currentGoods.value.stastsPlatformValIds.split(",");
  const traverse = tree => {
    for (let item of tree) {
      if (idsArr.includes(item.stastsId)) {
        return item;
      } else {
        if (item.children && item.children.length) {
          if (traverse(item.children)) {
            const option = traverse(item.children);
            editAtrrForm.value.push({
              stastsId: item.stastsId,
              stastsName: item.statsTitle,
              stastsVal: [option.statsTitle],
              stastsValId: [option.stastsId],
              stasType: item.stasType,
              isCommon: item.isCommon
            });
          }
        }
      }
    }
  };
  traverse(atrrData.value);
  // console.log("form", editAtrrForm.value);
};
onMounted(() => {
  getCategoryTreeData();
  getPlatformAttribute();
});
</script>

<style lang="scss" scoped>
.platform-attribute {
  max-height: calc(100vh - 170px);
  display: flex;
  font-size: 14px;
  overflow: hidden;

  > div {
    height: calc(100vh - 170px);
  }

  .side {
    width: 300px;
    min-width: 300px;
    background: #f5f7fa;

    .radio-goup {
      display: flex;
      width: calc(100% - 20px);
      margin: 20px auto 15px;

      > div {
        flex: 1;
        height: 32px;
        border: 1px solid #e1e6ed;
        text-align: center;
        line-height: 32px;
        color: #4e5969;
        cursor: pointer;
      }

      .radio-active {
        position: relative;
        border: 1px solid #007dff;
        z-index: 1;
        color: #007dff;
      }
    }

    [class*="attribute-item"] {
      height: 32px;
      padding: 0 10px;
      line-height: 32px;
      cursor: pointer;
    }

    .attribute-item-active {
      background: #d9e8ff;
    }
  }

  .container {
    flex: 1;
    padding: 20px 0 0 20px;
    box-sizing: border-box;

    .filter {
      height: 50px;
      border: 1px solid #e1e6ed;
      display: flex;
      gap: 50px;
      align-items: center;
      padding: 0 20px;

      ::v-deep(.el-form-item) {
        margin: 0;
      }

      .checked {
        white-space: nowrap;
      }
    }

    .table-head {
      background: #f2f6fc;
      align-items: center;
      height: 50px;
      color: #4e5969;
      margin-bottom: 10px;
      font-size: 14px;

      .el-col {
        text-align: center;
      }

      .el-col:nth-child(1) {
        display: flex;
        align-items: center;
        justify-content: start;

        .all {
          width: 40px;
          display: flex;
          justify-content: center;
          align-items: center;
        }

        .image-title {
          display: inline-block;
          width: 98px;
          text-align: left;
        }
      }
    }

    .table-list {
      height: calc(100vh - 300px);

      .el-checkbox-group {
        line-height: unset;
        font-size: unset;
      }

      .el-col {
        display: flex;
        align-items: center;
        padding: 10px 0;
        border-bottom: 1px solid #e1e6ed;
        border-left: 1px solid #e1e6ed;
        color: #4e5969;
        font-size: 14px;
        justify-content: center;
      }

      .el-col:nth-child(1) {
        justify-content: start;
      }

      .el-col:last-child {
        border-right: 1px solid #e1e6ed;
      }

      .goods {
        margin-bottom: 12px;

        .business-name {
          border: 1px solid #e1e6ed;
          display: flex;
          justify-content: space-between;
          background: #f2f6fc;
          font-size: 14px;
          line-height: 40px;
          padding-right: 10px;
          color: #007dff;

          .name {
            flex: 1;
            display: flex;
            margin-right: 50px;
          }

          > div:nth-child(2) {
            cursor: pointer;
            gap: 10px;
          }

          .all {
            min-width: 40px;
            width: 40px;
            display: flex;
            justify-content: center;
            align-items: center;

            ::v-deep(.el-checkbox__label) {
              padding: 0;
            }
          }
        }

        .remark {
          font-size: 14px;
          display: flex;
          border: 1px solid #ebeef5;
          border-top: none;
          padding: 12px;

          .label {
            color: #86909c;
            white-space: nowrap;
          }
        }
      }

      .table-operate {
        display: grid;
        grid-template-columns: 1fr;
        width: 100%;
        row-gap: 10px;

        ::v-deep(.el-button) {
          margin: 0 auto;
        }
      }

      .image {
        width: 80px;
        height: 80px;
        border-radius: 4px;
        margin: 0 18px 0 40px;
      }

      .info {
        color: #86909c;
        font-size: 12px;
        line-height: 20px;

        .red {
          color: red;
        }
      }
    }
  }
}

.tip {
  height: 32px;
  background: #d9edff;
  color: #3d3d3d;
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 0 10px;

  .el-icon {
    color: #0052d9;
    font-size: 18px;
  }
}

.batch-edit_content {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  height: calc(100vh - 170px);

  .atrr {
    height: 100%;
    border-right: 1px solid #e1e6ed;
    padding: 20px;
    box-sizing: border-box;
  }

  .goods-list {
    padding: 20px 20px 0 20px;

    ::v-deep(.goods-detail) {
      margin-bottom: 20px;
    }

    .atrr-str {
      position: relative;

      img {
        width: 20px;
        height: 20px;
        position: absolute;
        right: 0;
        bottom: 10px;
      }
    }

    &_item {
      background: #f5f7fa;
    }
  }

  > div {
    height: calc(100vh - 170px);
    box-sizing: border-box;
  }
}

.pagination {
  display: flex;
  justify-content: end;
}

.gray-bg {
  background: #f5f7fa;
  padding: 20px;
  box-sizing: border-box;
}
</style>
<style lang="scss">
.batch-edit {
  .el-drawer__header {
    margin-bottom: 20px;
  }

  .el-drawer__body {
    padding: 0;
  }

  .el-drawer__footer {
    box-shadow: 0px -3px 10px 0px rgba(4, 24, 48, 0.1);
    padding: 20px;
  }
}

.platformAttribute-drawer {
  .el-drawer__header {
    margin-bottom: 20px;
  }

  .el-drawer__body {
    padding-top: 0;
  }

  .el-drawer__footer {
    display: flex;
    justify-content: center;
  }
}
</style>
